package com.art.sunflower.service.impl;

import com.art.sunflower.enumeration.RoleType;
import com.art.sunflower.exception.NullAdminException;
import com.art.sunflower.mapper.AdminMapper;
import com.art.sunflower.mapper.UserMapper;
import com.art.sunflower.pojo.User;
import com.art.sunflower.service.AdminService;
import com.art.sunflower.util.Md5SaltTool;
import com.art.sunflower.util.MyPageInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class AdminServiceImpl implements AdminService {

    @Resource
    AdminMapper adminMapper;

    @Resource
    UserMapper userMapper;

    @Override
    public MyPageInfo getList(Integer pageSize, Integer pageNo) throws NullAdminException {
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> admin = adminMapper.selectList("admin");
        if (admin.size() == 0)
            throw new NullAdminException();
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(admin);
        return new MyPageInfo(pageInfo);
    }

    @Override
    public void add(String username, String password, String phone, String name) throws NoSuchAlgorithmException {
        userMapper.insertUserAll(username, Md5SaltTool.getEncryptedPwd(password), RoleType.admin, name, phone);
    }

    @Override
    public void update(Integer id, String username, String password, String phone, String name) throws NoSuchAlgorithmException, NullAdminException {
        User user = userMapper.selectUserById(id);
        if (user == null || user.getRole() != RoleType.admin) {
            throw new NullAdminException();
        } else {
            userMapper.updateUser(id, username, Md5SaltTool.getEncryptedPwd(password), name, phone);
        }
    }

    @Override
    public void delete(Integer id) throws NullAdminException {
        User user = userMapper.selectUserById(id);
        if (user == null || user.getRole() != RoleType.admin) {
            throw new NullAdminException();
        } else {
            userMapper.delete(id);
        }
    }

    @Override
    public Map<String, Object> getById(Integer id) throws NullAdminException {
        User user = userMapper.selectUserById(id);
        if (user == null) {
            throw new NullAdminException();
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("username", user.getUsername());
            map.put("realName", user.getRealName());
            map.put("phone", user.getPhone());
            return map;
        }
    }
}
